/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.specific.sge.status;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Map;

import jp.aist.gtrc.plus.scheduler.node.NodeInfo;
import jp.aist.gtrc.plus.scheduler.node.NodeResource;
import jp.aist.gtrc.plus.scheduler.specific.sge.jaxb.common.*;
import jp.aist.gtrc.plus.scheduler.status.ArchType;
import jp.aist.gtrc.plus.scheduler.status.JobStatus;
import jp.aist.gtrc.plus.scheduler.status.NodeStatus;
import jp.aist.gtrc.plus.scheduler.status.NodeStatusBase;
import jp.aist.gtrc.plus.scheduler.status.OSType;
import jp.aist.gtrc.plus.scheduler.util.HostUtil;
import jp.aist.gtrc.plus.scheduler.util.TextUtil;
import jp.aist.gtrc.plus.scheduler.util.TimeUtil;

public class SGENodeStatus extends NodeStatusBase {

	private final JAXBSGENode node;
	private final HashMap<String, SGEQInstance> qMap;
	private final HashMap<String, HLElement> loadMap;
	private SGEACL acl;
	private HashMap<String, String> attrMap;

	private static final String UNKNOWN_LOAD_VALUE = "";
	private static final SGEStatusManager statusMgr = SGEStatusManager.getInstance();

	public SGENodeStatus(JAXBSGENode node) {

		assert(node != null);
		this.node = node;
		this.qMap = new HashMap<String, SGEQInstance>();
		this.loadMap = new HashMap<String, HLElement>();

		String fqdn = HostUtil.makeFQDN(node.getEHName());
		this.node.setEHName(fqdn);
		this.acl = null;
		this.attrMap = null;

	}

	public int getCPUNum() {

		return node.getEHProcessors();

	}

	public String getName() {

		return node.getEHName();

	}

	private String getLoadValue(String name) {

		if (loadMap.size() == 0) {
			EHLoadList load = node.getEHLoadList();
			// "global" and "template" doesn't have <EH_load_list>
			if (load == null) {
				return UNKNOWN_LOAD_VALUE;
			}
			for (HLElement e : load.getHLElement()) {
				loadMap.put(e.getHLName(), e);
			}
		}

		HLElement load = loadMap.get(name);
		return (load != null) ? load.getHLValue() : UNKNOWN_LOAD_VALUE;

	}

	private String getArch() {

		// return value maybe "lx26-x86", "sol-sparc" etc
		return getLoadValue("arch");

	}

	public String toString() {

		StringBuffer sb = new StringBuffer();
		sb.append("Node ");
		sb.append(getName());
		sb.append(": ncpu=");
		sb.append(getCPUNum());

		// "global" and "template" doesn't have <EH_load_list>
		for (HLElement e : loadMap.values()) {
			sb.append(String.format(Locale.US, "\n\t%s\t%s%tc",
					e.getHLName(), e.getHLValue(),
					TimeUtil.makeCalendarFromSec(e.getHLLastUpdate())));
		}
		sb.append("\nACL ");
		sb.append(getAcl().toString());

		return sb.toString();

	}

	public boolean isAlive() {

		return (getLoadValue("load_avg") != UNKNOWN_LOAD_VALUE);

	}

	public boolean isIdle() {

		// SGENodeStatus information is updated every 40 seconds.
		// "num_running_jobs" is not "current" value,
		// which maybe 40 seconds before information.
		//return (getCPUNum() >= getInt("num_running_jobs"));

		return (getUsedSlotNum() < getTotalSlotNum());

	}

	public double getLoadAverage() {

		String s = getLoadValue("load_avg");
		if (s != UNKNOWN_LOAD_VALUE)
			return Double.parseDouble(s);
		else
			return 0.0;

	}

	public OSType getOSType() {

		return SGEArch.getOSType(getArch());

	}

	public ArchType getArchType() {

		return SGEArch.getArchType(getArch());

	}

	public long getPhysicalMemory() {

		String s = getLoadValue("mem_total");
		if (s != UNKNOWN_LOAD_VALUE) {
			try {
				return (long)TextUtil.calcSize(s);
			} catch (NumberFormatException e) {
				// fall-through
			}
		}
		return 0;

	}

	public int getRunningJobNum() {

		int n = 0;
		for (SGEQInstance qins: getAllQInstances()) {
			n += qins.getUsedSlotNum();
		}
		return n;

	}

	public void addQInstance(SGEQInstance ins) {

		// overwrite 'ins' if already exists
		qMap.put(ins.getQname(), ins);

	}

	public Collection<SGEQInstance> getAllQInstances() {

		return qMap.values();

	}

	public SGEQInstance getQInstances(String qName) {

		return qMap.get(qName);

	}

	public int getTotalSlotNum() {

		int n = 0;
		for (SGEQInstance ins : getAllQInstances()) {
			n += ins.getTotalSlotNum();
		}
		return n;

	}

	public int getUsedSlotNum() {

		int n = 0;
		for (SGEQInstance ins : getAllQInstances()) {
			n += ins.getUsedSlotNum();
		}
		return n;

	}

	private Collection<USElement> getUSentries(AUSRLISTValue acl) {

		return (acl == null) ? null : acl.getUSElement();

	}

	private Collection<UPElement> getUPentries(APRJLISTValue acl) {

		return (acl == null) ? null : acl.getUPElement();

	}

	private SGEACL makeAcl() {

		SGEUserACL userAcl = SGEUserACL.getInstance(
				getUSentries(node.getEHAcl()),
				getUSentries(node.getEHXacl()));
		SGEProjectACL projAcl = SGEProjectACL.getInstance(
				getUPentries(node.getEHPrj()),
				getUPentries(node.getEHXprj()));
		return new SGEACL(userAcl, projAcl);

	}

	public SGEACL getAcl() {

		if (acl == null)
			acl = makeAcl();
		return acl;

	}

	public static SGENodeStatus getSGENodeStatus(NodeInfo node) {

		NodeStatus status = node.getStatus();
		if (status instanceof SGENodeStatus) {
			return (SGENodeStatus)status;
		} else if (status instanceof SGEQInstance) {
			SGEQInstance ins = (SGEQInstance)status;
			SGENodeStatus nodeStatus = (SGENodeStatus)ins.getNode();
			return nodeStatus;
		} else {
			assert(false);
			return null;
		}

	}

	public Collection<SGEJobID> getDirtyTasks() {

		LinkedList<SGEJobID> jidList = new LinkedList<SGEJobID>();
		EHRescheduleUnknownList unkList = node.getEHRescheduleUnknownList();
		if (unkList != null) {
			for (RUElement e : unkList.getRUElement()) {
				SGEJobID jid = new SGEJobID(
						e.getRUJobNumber(), e.getRUTaskNumber());
				jidList.add(jid);
			}
		}
		return jidList;

	}

	public NodeResource getResource() {

		return SGENodeResource.getInstance(this);

	}

	public String getAttribute(String attr) {

		return getAttributeMap().get(attr);

	}

	public Map<String, String> getAttributeMap() {

		if (attrMap != null)
			return attrMap;

		attrMap = new HashMap<String, String>();
		for (HLElement e : loadMap.values()) {
			attrMap.put(e.getHLName(), e.getHLValue());
		}
		EHConsumableConfigList ccList = node.getEHConsumableConfigList();
		if (ccList != null) {
			for (CEElement e : ccList.getCEElement()) {
				attrMap.put(e.getCEName(), e.getCEStringval());
			}
		}

		return attrMap;

	}

	public Collection<JobStatus> getJobs() {

		return statusMgr.getJobsOnNode(getName());

	}

}
